/*
 * @lc app=leetcode.cn id=922 lang=javascript
 *
 * [922] 按奇偶排序数组 II
 */

// @lc code=start
/**
 * @param {number[]} nums
 * @return {number[]}
 */
var sortArrayByParityII = function (nums) {
  let i = 0, j = 0;
  while (nums[i] % 2 === 1) i++;
  while (nums[j] % 2 === 0) j++;
  for (let k = 0; k < nums.length; k++) {
    if (nums[k] % 2 === k % 2) {
      while (i === k || nums[i] % 2 === 1) i++;
      while (j === k || nums[j] % 2 === 0) j++;
    } else {
      [nums[i], nums[j]] = [nums[j], nums[i]];
      do { i++; } while (nums[i] % 2 === 1);
      do { j++; } while (nums[j] % 2 === 0);
    }
  }
  return nums;
};
// @lc code=end
